package com.bruce.asurada.sso.controller;

import com.bruce.asurada.common.Result;
import com.bruce.asurada.sso.util.ServiceHealthChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务健康检查控制器
 * @author Bruce
 */
@Slf4j
@RestController
@RequestMapping("/health")
public class ServiceHealthController {

    @Autowired
    private ServiceHealthChecker serviceHealthChecker;

    /**
     * 检查指定服务的健康状态
     */
    @GetMapping("/check/{serviceName}")
    public Result<Map<String, Object>> checkService(@PathVariable String serviceName) {
        Map<String, Object> result = new HashMap<>();
        
        boolean available = serviceHealthChecker.isServiceAvailable(serviceName);
        List<ServiceInstance> instances = serviceHealthChecker.getServiceInstances(serviceName);
        
        result.put("serviceName", serviceName);
        result.put("available", available);
        result.put("instanceCount", instances != null ? instances.size() : 0);
        result.put("instances", instances);
        
        return Result.success(result);
    }

    /**
     * 检查用户服务的健康状态
     */
    @GetMapping("/user-service")
    public Result<Map<String, Object>> checkUserService() {
        return checkService("asurada-user");
    }
}